'use strict';

const Controller = require('egg').Controller;
const jwt=require('jsonwebtoken')
class zcController extends Controller {
  async index() {
    const { ctx } = this;
   //获取你的参数查找内容存不存在
   let {username,pwd,name}=ctx.request.body
   let res=await ctx.service.user.have(username,pwd,name)
    if(res.length)
    {
      ctx.body={
        code:1,
        msg:"已经注册过啦"
      }
    }
    else{
      //将数据传
      let res=await ctx.service.user.zcgo(username,ctx.helper.help(pwd),name)
      //判断有没有注册成功
        if(res.affectedRows===1)
        {
          ctx.body={
            code:0,
            msg:"注册成功了"
          }
        }
        else {
        ctx.body = {
            code: 1,
            msg: '注册失败'
        }
    }
    }

  }
  async dl()
  {
    let {ctx}=this
    let {username,pwd}=ctx.request.body
  if(!username||!pwd)
  {
    ctx.body={
      code:0,
      msg:"参数不全"
    }
  }
    let res=await ctx.service.user.logins(username,ctx.helper.help(pwd))
   //判断是否登陆成功
   if(res.length)
   {
   let token= jwt.sign({ ...res[0]}, 'secret', { expiresIn: '1h' });
    ctx.body={
      code:1,
      msg:"登陆成功",
      token,
      uid:res[0].id//用户id
    }
   }
   else{
    ctx.body={
      code:0,
      msg:"密码或账户信息不全"
    }
   }
  }
}

module.exports = zcController;